﻿using Aliyun.OpenServices.OpenStorageService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace WebMvc.App.Code.Extend.Yun
{
	class ALiUp : IUploadable
	{
		public void Initial(string bucket, string key, string fname, string accessId, string accessKey, string secretKey)
		{
			OssClient _ossClient = new OssClient(accessId, accessKey);	
			var request = new InitiateMultipartUploadRequest(bucket, key);			
			_ossClient.InitiateMultipartUpload(request);			
		}

		public bool Upload(string bucket, string key, string fname, string accessId, string accessKey, string secretKey, int partSize)
		{
			OssClient _ossClient = new OssClient(accessId, accessKey);
			var request = new InitiateMultipartUploadRequest(bucket, key);
			var uploadId = _ossClient.InitiateMultipartUpload(request).UploadId; //Initial(bucket, key, fname, accessId, accessKey, endpoint).UploadId;

			var fi = new FileInfo(fname);
			var fileSize = fi.Length;
			var partCount = fileSize / partSize;
			if (fileSize % partSize != 0)
			{
				partCount++;
			}

			var partETags = new List<PartETag>();
			for (var i = 0; i < partCount; i++)
			{
				using (var fs = File.Open(fname, FileMode.Open))
				{
					var skipBytes = (long)partSize * i;
					fs.Seek(skipBytes, 0);
					var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
					var upRequest = new UploadPartRequest(bucket, key, uploadId)
					{
						InputStream = fs,
						PartSize = size,
						PartNumber = i + 1
					};
					var result = _ossClient.UploadPart(upRequest);
					partETags.Add(result.PartETag);
				}
			}
			var completeMultipartUploadRequest =
				new CompleteMultipartUploadRequest(bucket, key, uploadId);
			foreach (var partETag in partETags)
			{
				completeMultipartUploadRequest.PartETags.Add(partETag);
			}
			var ossRet = _ossClient.CompleteMultipartUpload(completeMultipartUploadRequest);
			if(!string.IsNullOrEmpty(ossRet.Location))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
}
